package com.mirror.controller;

import com.mirror.entity.building.Bed;
import com.mirror.entity.building.Building;
import com.mirror.entity.building.Floor;
import com.mirror.entity.building.Room;
import com.mirror.entity.oldman.Employees;
import com.mirror.entity.oldman.Result;
import com.mirror.repository.*;
import com.mirror.util.CommonUtil;
import com.mirror.util.ResultUtil;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.json.JSONArray;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;

@Api(description = "建筑管理")
@RestController
@RequestMapping("building")
public class BuildingController {


    @Autowired
    private BuildingRepository buildingRepository;
    @Autowired
    private FloorRepository floorRepository;
    @Autowired
    private RoomRepository roomRepository;
    @Autowired
    private EmployeesRepository employeesRepository;
    @Autowired
    private BedRepository bedRepository;
    @Autowired
    /*private RegistBedRepository registBedRepository;
    @Autowired
    private OldmanRepository oldmanRepository;*/


    @ApiOperation(value = "建筑列表无分页", notes = "建筑列表")
    @GetMapping("/list")
    public Result list() {
        List<Building> blist = buildingRepository.findAllByIsdelOrderByBuildingName(false);
        return ResultUtil.success(blist);
    }

    @ApiOperation(value = "建筑列表无分页", notes = "建筑列表")
    @GetMapping("/all1")
    public Result all1() {
        JSONObject jso = new JSONObject();
        JSONObject jo = new JSONObject();
        JSONArray json = new JSONArray();
        JSONArray ja = new JSONArray();
        List<Building> bs = buildingRepository.findAllByIsdelOrderByBuildingName(false);
        if (bs.size() > 0) {
            for (Building b : bs) {
                JSONObject jo1 = new JSONObject();
                JSONArray ja1 = new JSONArray();
                jo1.put("buildingId", b.getId());
                jo1.put("name", b.getBuildingName());
                jo1.put("floorsNum", b.getFloorsNum());
                jo1.put("open", true);
                jo1.put("memo", b.getMemo());
                List<Floor> fs = floorRepository.findAllByIsdelAndBuildingOrderByFloorName(false, b);
                if (fs.size() > 0) {
                    for (Floor f : fs) {
                        if (f.getFloorName().length() == 4) {
                            JSONArray ja2 = new JSONArray();
                            JSONObject jo2 = new JSONObject();
                            jo2.put("floorId", f.getId());
                            jo2.put("roomsNum", f.getRoomsNum());
                            jo2.put("name", f.getFloorName());
                            jo2.put("open", false);
                            jo2.put("fMemo", f.getMemo());
                            List<Room> rs = roomRepository.findAllByIsdelAndFloorOrderByRoomName(false, f);
                            if (rs.size() > 0) {
                                for (Room r : rs) {
                                    JSONObject jo3 = new JSONObject();
                                    jo3.put("roomId", r.getId());
                                    jo3.put("bedsNum", r.getBedsNum());
                                    jo3.put("open", false);
                                    jo3.put("name", r.getRoomName());
                                    jo3.put("rMemo", r.getMemo());
                                    jo3.put("RFID", "room:" + r.getId());
                                    ja2.put(jo3);
                                }
                            }
                            jo2.put("children", ja2);
                            ja1.put(jo2);
                        }
                    }
                    for (Floor f : fs) {
                        if (f.getFloorName().length() == 5) {
                            JSONArray ja2 = new JSONArray();
                            JSONObject jo2 = new JSONObject();
                            jo2.put("floorId", f.getId());
                            jo2.put("roomsNum", f.getRoomsNum());
                            jo2.put("name", f.getFloorName());
                            jo2.put("open", false);
                            jo2.put("fMemo", f.getMemo());
                            List<Room> rs = roomRepository.findAllByIsdelAndFloorOrderByRoomName(false, f);
                            if (rs.size() > 0) {
                                for (Room r : rs) {
                                    JSONObject jo3 = new JSONObject();
                                    jo3.put("roomId", r.getId());
                                    jo3.put("bedsNum", r.getBedsNum());
                                    jo3.put("open", false);
                                    jo3.put("name", r.getRoomName());
                                    jo3.put("rMemo", r.getMemo());
                                    jo3.put("RFID", "room:" + r.getId());
                                    ja2.put(jo3);
                                }
                            }
                            jo2.put("children", ja2);
                            ja1.put(jo2);
                        }
                    }
                }
                jo1.put("children", ja1);
                ja.put(jo1);
            }
        }
        jo.put("children", ja);
        jo.put("name", "楼房管理");
        jo.put("open", true);
        json.put(jo);
        jso.put("list", json);
        return ResultUtil.success(jso.toString());
    }

    @ApiOperation(value = "建筑列表无分页", notes = "建筑列表")
    @GetMapping("/all")
    public Result all() {
        JSONObject jo = new JSONObject();
        JSONArray ja = new JSONArray();
        List<Building> bs = buildingRepository.findAllByIsdelOrderByBuildingName(false);
        if (bs.size() > 0) {
            for (Building b : bs) {
                JSONObject jo1 = new JSONObject();
                JSONArray ja1 = new JSONArray();
                jo1.put("buildingId", b.getId());
                jo1.put("buildingName", b.getBuildingName());
                jo1.put("floorsNum", b.getFloorsNum());
                jo1.put("memo", b.getMemo());
                List<Floor> fs = floorRepository.findAllByIsdelAndBuildingOrderByFloorName(false, b);
                if (fs.size() > 0) {
                    for (Floor f : fs) {
                        JSONArray ja2 = new JSONArray();
                        JSONObject jo2 = new JSONObject();
                        jo2.put("fId", f.getId());
                        jo2.put("fNum", f.getRoomsNum());
                        jo2.put("fName", f.getFloorName());
                        jo2.put("fMemo", f.getMemo());
                        List<Room> rs = roomRepository.findAllByIsdelAndFloorOrderByRoomName(false, f);
                        if (rs.size() > 0) {
                            for (Room r : rs) {
                                JSONObject jo3 = new JSONObject();
                                jo3.put("rId", r.getId());
                                jo3.put("rNum", r.getBedsNum());
                                jo3.put("rName", r.getRoomName());
                                jo3.put("rMemo", r.getMemo());
                                jo3.put("RFID", "room:" + r.getId());
                                jo3.put("jordanRFID", "jordan:" + r.getId());
                                ja2.put(jo3);
                            }
                        }
                        jo2.put("roomInfo", ja2);
                        ja1.put(jo2);
                    }
                }
                jo1.put("floorInfo", ja1);
                ja.put(jo1);
            }
        }
        jo.put("list", ja);
        jo.put("children", ja);
        jo.put("name", "楼房管理");
        jo.put("open", true);
        return ResultUtil.success(jo.toString());
    }

    @ApiOperation(value = "建筑列表无分页", notes = "建筑列表")
    @GetMapping("/all2")
    public Result all2() {
        JSONObject jso = new JSONObject();

        JSONObject jo = new JSONObject();
        JSONArray json = new JSONArray();
        JSONArray ja = new JSONArray();
        List<Building> bs = buildingRepository.findAllByIsdelOrderByBuildingName(false);
        if (bs.size() > 0) {
            for (Building b : bs) {
                JSONObject jo1 = new JSONObject();
                JSONArray ja1 = new JSONArray();
                jo1.put("buildingId", b.getId());
                jo1.put("name", b.getBuildingName());
                jo1.put("floorsNum", b.getFloorsNum());
                jo1.put("open", false);
                jo1.put("memo", b.getMemo());
                List<Floor> fs = floorRepository.findAllByIsdelAndBuildingOrderByFloorName(false, b);
                if (fs.size() > 0) {
                    for (Floor f : fs) {
                        JSONArray ja2 = new JSONArray();
                        JSONObject jo2 = new JSONObject();
                        jo2.put("fId", f.getId());
                        jo2.put("fNum", f.getRoomsNum());
                        jo2.put("name", f.getFloorName());
                        jo2.put("open", false);
                        jo2.put("fMemo", f.getMemo());
                        List<Room> rs = roomRepository.findAllByIsdelAndFloorOrderByRoomName(false, f);
                        if (rs.size() > 0) {
                            for (Room r : rs) {
                                JSONArray ja3 = new JSONArray();
                                JSONObject jo3 = new JSONObject();
                                jo3.put("rId", r.getId());
                                jo3.put("rNum", r.getBedsNum());
                                jo3.put("open", false);
                                jo3.put("name", r.getRoomName());
                                jo3.put("rMemo", r.getMemo());
                                jo3.put("RFID", "room:" + r.getId());
                                List<Bed> beds = bedRepository.findAllByIsdelAndRoomOrderByBedName(false, r);
                                if (bs.size() > 0) {
                                    for (Bed bed : beds) {
                                        JSONObject jo4 = new JSONObject();
                                        jo4.put("bedId", bed.getId());
                                        jo4.put("bedNum", bed.getBedNum());
                                        jo4.put("open", false);
                                        jo4.put("name", bed.getBedName());
                                        jo4.put("rMemo", bed.getMemo());
                                        /*Oldman old = oldmanRepository.findAllByBedid(bed.getId());
                                        if (old != null) {
                                            jo4.put("hasOld", true);
                                        } else {
                                            jo4.put("hasOld", false);
                                            ja3.put(jo4);
                                        }*/
                                    }
                                }
                                jo3.put("children", ja3);
                                if (ja3.length() > 0) {
                                    ja2.put(jo3);
                                }
                            }
                        }
                        jo2.put("children", ja2);
                        if (ja2.length() > 0) {
                            ja1.put(jo2);
                        }
                    }
                }
                jo1.put("children", ja1);
                if (ja1.length() > 0) {
                    ja.put(jo1);
                }
            }
        }
        jo.put("children", ja);
        jo.put("name", "楼房管理");
        jo.put("open", true);
        json.put(jo);
        jso.put("list", json);
        return ResultUtil.success(jso.toString());
    }

    @ApiOperation(value = "建筑列表", notes = "建筑列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"page\": \"页码\",\"size\": \"每页数量\"}", required = true, dataType = "String"),
    })
    @PostMapping("/pagelist")
    public Result atList(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        int page = tempData.getInt("page");
        int size = tempData.getInt("size");
        Sort sort = new Sort(Sort.Direction.DESC, "createDate");
        Pageable pageable = new PageRequest(page, size, sort);
        Page<Building> atPage = buildingRepository.findAllByIsdelOrderByBuildingName(pageable, false);
        return ResultUtil.success(atPage);
    }

    @ApiOperation(value = "建筑列表", notes = "建筑列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"search\": \"内容\"}", required = true, dataType = "String"),
    })
    @PostMapping("/search")
    public Result search(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String[] search = tempData.getString("search").split(":");
        if (search.length != 2) {
            return ResultUtil.error(-1, "搜索内容有误！");
        }
        String type = search[0];
        String id = search[1];
        JSONObject jo = new JSONObject();
        //搜房间id
        if ("room".equals(type)) {
            Room r = roomRepository.findOne(id);
            if (r != null) {
                jo.put("tag", "room");
                jo.put("bedsNum", r.getBedsNum());
                jo.put("roomId", r.getId());
                jo.put("roomName", r.getRoomName());
                jo.put("roomMemo", r.getMemo());
                Floor f = r.getFloor();
                if (f != null) {
                    jo.put("floorId", f.getId());
                    jo.put("roomsNum", f.getRoomsNum());
                    jo.put("floorName", f.getFloorName());
                    jo.put("floorMemo", f.getMemo());
                    Building b = f.getBuilding();
                    if (b != null) {
                        jo.put("buildingId", b.getId());
                        jo.put("buildingFloorsNum", b.getFloorsNum());
                        jo.put("buildingName", b.getBuildingName());
                        jo.put("buildingMemo", b.getMemo());
                    }
                }

                List<Bed> beds = bedRepository.findAllByIsdelAndRoomOrderByBedName(false, r);
                JSONArray ja = new JSONArray();
                if (beds.size() > 0) {
                    for (Bed b : beds) {
                        JSONObject jo1 = new JSONObject();
                        jo1.put("bedId", b.getId());
                        jo1.put("bedName", b.getBedName());
                        jo1.put("bedNum", b.getBedNum());
                        jo1.put("memo", b.getMemo());
                        /*RegistBed rb = registBedRepository.findAllByBed(b);
                        if (rb != null) {
                            jo1.put("oldmanId", rb.getOldman().getId());
                            jo1.put("oldmanName", rb.getOldman().getName());
                        } else {
                            jo1.put("oldmanId", "");
                            jo1.put("oldmanName", "");
                        }*/
                        ja.put(jo1);
                    }
                    jo.put("info", ja);
                }
            }
        } else if ("jordan".equals(type)) {
            Room j = roomRepository.findOne(id);
            if (j != null) {
                jo.put("roomId", j.getId());
                jo.put("roomName", j.getRoomName());
                jo.put("tag", "jordan");
            }
        } else if ("doctor".equals(type) || "caregivers".equals(type)) {
            Employees e = employeesRepository.findOne(id);
            if (e != null) {
                jo.put("eId", e.getId());
                jo.put("eName", e.getName());
                jo.put("tag", "employees");
            }
        } else {
           /* //搜索床位信息
            RegistBed rb = null;
            if ("oldman".equals(type)) {
                rb = registBedRepository.findAllByOldman_Id(id);
            } else if ("bed".equals(type)) {
                rb = registBedRepository.findAllByBed_Id(id);
            }
            if (rb != null) {
                jo.put("oldmanId", rb.getOldman().getId());
                jo.put("oldmanName", rb.getOldman().getName());
                jo.put("bedId", rb.getBed().getId());
                jo.put("bedName", rb.getBed().getBedName());
                if ("oldman".equals(type)) {
                    jo.put("tag", "oldman");
                } else if ("bed".equals(type)) {
                    jo.put("tag", "bed");
                }
            }*/
        }
        return ResultUtil.success(jo.toString());
    }

    @ApiOperation(value = "建筑列表", notes = "建筑列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"id\":\"房间id\"}", required = true, dataType = "String"),
    })
    @PostMapping("/showRoom")
    public Result showRoom(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String id = tempData.optString("id");

        JSONObject jo = new JSONObject();
        Room r = roomRepository.findOne(id);
        if (r != null) {
            List<Bed> beds = bedRepository.findAllByIsdelAndRoomOrderByBedName(false, r);
            JSONArray ja = new JSONArray();
            if (beds.size() > 0) {
                for (Bed b : beds) {
                    JSONObject jo1 = new JSONObject();
                    jo1.put("bedId", b.getId());
                    jo1.put("bedName", b.getBedName());
                    jo1.put("bedNum", b.getBedNum());
                    jo1.put("memo", b.getMemo());
                    jo1.put("bedRFID", "bed:" + b.getId());
                    /*RegistBed rb = registBedRepository.findAllByBed(b);
                    if (rb != null) {
                        Oldman om = rb.getOldman();
                        if (om != null) {
                            jo1.put("oldmanId", om.getId());
                            String cardno = "";
                            if (om.getCardno().length() == 15) {
                                cardno = CommonUtil.conver15CardTo18(om.getCardno());
                            } else {
                                cardno = om.getCardno();
                            }
                            String birthday = cardno.substring(6, 14);
                            try {
                                Date birthdate = new SimpleDateFormat("yyyyMMdd")
                                        .parse(birthday);
                                jo1.put("age", CommonUtil.getAge(birthdate));
                            } catch (ParseException e1) {
                                e1.printStackTrace();
                            }
                            jo1.put("name", om.getName());
                            jo1.put("sex", om.getSex());
                            jo1.put("oldmanRFID", "oldman:" + rb.getOldman().getId());
                        } else {
                            jo1.put("oldmanId", "");
                            jo1.put("age", "");
                            jo1.put("name", "");
                            jo1.put("sex", "");
                            jo1.put("oldmanRFID", "");
                        }
                    }*/
                    ja.put(jo1);
                }
                jo.put("info", ja);
            }
        }
        return ResultUtil.success(jo.toString());
    }

    @ApiOperation(value = "建筑列表", notes = "建筑列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"building\":\"建筑id\",\"floor\":\"楼层id\",\"room\":\"房间id\"}", required = true, dataType = "String"),
    })
    @PostMapping("/searchBuilding")
    public Result searchBuilding(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String building = tempData.optString("building");
        String floor = tempData.optString("floor");
        String room = tempData.optString("room");
        if (CommonUtil.isNOT_Null(room)) {
            List<Bed> atPage = bedRepository.findAllByIsdelAndRoom_IdOrderByBedName(false, room);
            return ResultUtil.success(atPage);
        } else if (CommonUtil.isNOT_Null(floor)) {
            List<Room> atPage = roomRepository.findAllByIsdelAndFloor_IdOrderByRoomName(false, floor);
            return ResultUtil.success(atPage);
        } else if (CommonUtil.isNOT_Null(building)) {
            List<Floor> atPage = floorRepository.findAllByIsdelAndBuilding_IdOrderByFloorName(false, building);
            return ResultUtil.success(atPage);
        } else {
            List<Building> atPage = buildingRepository.findAllByIsdelOrderByBuildingName(false);
            return ResultUtil.success(atPage);
        }

    }


    @ApiOperation(value = "添加建筑", notes = "添加建筑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"memo\": \"备注\",\"buildingName\": \"建筑名\"}", required = true, dataType = "String"),
    })
    @PostMapping("/save")
    public Result save(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String memo = tempData.optString("memo");
        String buildingName = tempData.getString("buildingName");
        Building a = new Building();
        a.setCreateDate(new Date());
        a.setBuildingName(buildingName);
        a.setMemo(memo);
        a.setFloorsNum(0);
        a.setIsdel(false);
        return ResultUtil.success(buildingRepository.save(a));
    }

    @ApiOperation(value = "修改建筑", notes = "修改建筑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"id\": \"建筑id\",\"buildingName\": \"建筑名\",\"memo\": \"备注\",\"floorsNum\": \"楼层数\"}", required = true, dataType = "String"),
    })
    @PostMapping("/edit")
    public Result edit(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String id = tempData.getString("id");
        String buildingName = tempData.getString("buildingName");
        String memo = tempData.optString("memo");
        int floorsNum = tempData.getInt("floorsNum");
        Building a = buildingRepository.findOne(id);
        if (a == null) {
            return ResultUtil.error(-1, "获取建筑失败！");
        }
        a.setBuildingName(buildingName);
        a.setMemo(memo);
        a.setFloorsNum(floorsNum);
        return ResultUtil.success(buildingRepository.save(a));
    }

    @ApiOperation(value = "删除建筑", notes = "删除建筑")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "data", value = "{\"id\": \"建筑id\"}", required = true, dataType = "String"),
    })
    @PostMapping("/del")
    public Result del(@RequestBody String data) {
        JSONObject tempData = new JSONObject(data);
        String id = tempData.getString("id");
        Building a = buildingRepository.findOne(id);
        if (a == null) {
            return ResultUtil.error(-1, "获取建筑失败！");
        }
        a.setIsdel(true);
        return ResultUtil.success(buildingRepository.save(a));
    }

}

